﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using NPOI.POIFS.FileSystem;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;

namespace CoreShop.App
{
    public partial class frmfoodtask : UIForm
    {
        private List<corecmsfoodtask> taskList = null;
        static System.Timers.Timer timer_focus = null;
        private bool isFocusInput = false;
        public int taskType = 1;//0整单做法，1单品做法

        public frmfoodtask()
        {
            InitializeComponent();
            if (timer_focus == null)
            {
                timer_focus = new System.Timers.Timer();
                timer_focus.Interval = 200;
                timer_focus.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
                timer_focus.Enabled = true;
            }
        }
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (!isFocusInput)
                {
                    this.txtInput.Invoke(new Action(() =>
                    {
                        this.txtInput.Focus();
                    }));
                }
            }
            catch { }
        }
        public void AddType(string type)
        {
            if (type.IsNullOrEmpty()) return;
            UIMenuItemSeparator item = new UIMenuItemSeparator(type, 40);
            item.SetOtherMode();
            layTaskList.Add(item);
        }

        public void AddItems(string type, List<corecmsfoodtask> items, bool autoWidth, Size itemSize, int height, int maxSelected = int.MaxValue)
        {
            string sName = "";
            UIMultiButtons buttons = new UIMultiButtons();
            buttons.Width = layTaskList.Width - 30;
            buttons.Height = height;
            buttons.TagString = type;
            buttons.AutoWidth = autoWidth;
            buttons.MaxSelected = maxSelected;
            buttons.ItemSize = itemSize;
            buttons.OnOverSelectedCount += Buttons_OnOverSelectedCount;
            foreach (var item in items)
            {
                sName = item.name;
                if ((item.price > 0) && (item.addPriceWay > (int)GlobalEnumVars.AddPriceWay.UnAdd))
                    sName = item.name + string.Format(" ¥{0}", item.price);
                buttons.Add(sName, item.id, item.selectedFlag);
            }
            layTaskList.Add(buttons);
        }


        private void Buttons_OnOverSelectedCount(object sender, System.EventArgs e)
        {
            UIMultiButtons button = (UIMultiButtons)sender;
            UIMessageTip.ShowWarning(button, button.TagString + "只能最多选择" + button.MaxSelected + "项");
        }

        private void btnOk_Click(object sender, System.EventArgs e)
        {
            if (SaveOrderingTask(1)) this.DialogResult = System.Windows.Forms.DialogResult.OK;
            //DoValueChanged(this, buttons);
        }

        private bool SaveOrderingTask(int type)
        {
            taskType = type;
            var buttons = this.GetControls<UIMultiButtons>(true);
            foreach (var task in taskList)
            {
                task.selectedFlag = false;
            }
            foreach (UIMultiButtons button in buttons)
            {
                long[] taskIds = button.SelectedButtonsValues;
                var taskSels = taskList.Where(p => taskIds.Contains(p.id)).ToList();
                foreach (var taskSel in taskSels)
                {
                    taskSel.selectedFlag = true;
                }
            }

            string sSelectTxt = "";
            foreach (var foodtask in taskList)
            {
                if (foodtask.selectedFlag)
                {
                    sSelectTxt = sSelectTxt + foodtask.name;
                }
            }
            if (sSelectTxt.Length > 600)
            {
                UIMessageBox.Show("选择的数据过多。无法保存。", "保存失败", UIStyle.Orange, UIMessageBoxButtons.OK);
                return false;
            }
            var bl = new corecmsfoodorderingServices().SaveOrderingTask((this.Owner as FOrdering).orderingSelected, taskList, type);
            if (!bl)
            {
                UIMessageBox.Show("保存失败。", "系统出错-SaveOrderingFeed:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return false;
            }
            return true;
        }

        private void frmfoodtask_Load(object sender, System.EventArgs e)
        {
            this.Text = "商品：" + (this.Owner as FOrdering).orderingSelected.name;
            taskList = new corecmsfoodtaskServices().QueryFromOrdering((this.Owner as FOrdering).orderingSelected.id, (this.Owner as FOrdering).orderingSelected.foodId, AppConstVars.sysStore.id);
            if (taskList.Count == 0)
            {
                ShowInfoTip("没有添加做法资料,无法选择。");
                btnOk.Visible = false;
                return;
            }
            string taskTypeName = "";
            foreach (var task in taskList)
            {
                if (task.pinYin.IsNullOrEmpty()) task.pinYin = "";
                if (taskTypeName != task.tastTypeName)
                {
                    taskTypeName = task.tastTypeName;
                    AddType(taskTypeName);
                    var taskGroup = taskList.Where(p => p.taskTypeId == task.taskTypeId).ToList();
                    int rows = CommFunc.ConvertToInt32(Math.Ceiling(taskGroup.Count / 5.0));
                    AddItems(taskTypeName, taskGroup, false, new Size(130, 40), 50 * rows, taskGroup.Count);
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void txtInput_TextChanged(object sender, EventArgs e)
        {
            string sLoca = txtInput.Text;
            var taskListLoca = taskList.Where(p => p.name.Contains(sLoca) || p.pinYin.Contains(sLoca)).ToList();
            layTaskList.Clear();
            string taskTypeName = "";
            foreach (var task in taskListLoca)
            {
                if (taskTypeName != task.tastTypeName)
                {
                    taskTypeName = task.tastTypeName;
                    AddType(taskTypeName);
                    var taskGroup = taskListLoca.Where(p => p.taskTypeId == task.taskTypeId).ToList();
                    int rows = CommFunc.ConvertToInt32(Math.Ceiling(taskGroup.Count / 5.0));
                    AddItems(taskTypeName, taskGroup, false, new Size(130, 40), 50 * rows, taskGroup.Count);
                }
            }
        }

        private void btnUseTask_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtInput.Text))
            {
                UIMessageBox.Show("请输入备注的内容。", "提示:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            (this.Owner as FOrdering).GetOrderingSelected();
            (this.Owner as FOrdering).orderingSelected.remark = txtInput.Text;
            var bl = new corecmsfoodorderingServices().Update((this.Owner as FOrdering).orderingSelected);
            if (bl)
            {
                taskType = 1;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        private void txtInput_Leave(object sender, EventArgs e)
        {
            isFocusInput = false;
        }

        private void txtInput_Enter(object sender, EventArgs e)
        {
            isFocusInput = true;
        }

        private void btnOKAll_Click(object sender, EventArgs e)
        {
            if (SaveOrderingTask(0)) this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnUseTaskAll_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtInput.Text))
            {
                UIMessageBox.Show("请输入备注的内容。", "提示:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            var bl = new corecmsfoodorderingServices().Update(a => new corecmsfoodordering()
            {
                remark = txtInput.Text,
            }, a => a.orderId == (this.Owner as FOrdering).orderingSelected.orderId);
            if (bl)
            {
                taskType = 0;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }
    }
}
